const cheerio = require('cheerio');

String.prototype.remove = function (...strs) {
  let _this = this;
  strs.forEach(str => {
    _this = _this.replace(new RegExp(str, 'g'), '');
  });
  return _this;
};


// 获取标题
function getTitle($) {
  return $('h1>span').text();
}


function getInfo($) {
  const info = {};
  const infoEle = $('#info');
  const spanEles = [...infoEle.children()];

  spanEles.forEach(spanEle => {
    const plText = $(spanEle).children('.pl').text();
    if (plText) {
      let value;
      if ($(spanEle).find('a').length > 0) {
        // 处理有多个链接的情况（如编剧、主演）
        value = [...$(spanEle).find('a')].map(a => a.children[0].data);
      } else {
        // 处理单一值的情况（如类型、制片国家/地区、语言、上映日期、片长、又名、IMDb）
        value = $(spanEle).contents().filter((_, content) => content.type === 'text')[1].data.trim();
      }
      info[plText.replace(':', '').trim()] = value;
    }
  });
  return info;
}

function getIntro($) {
  const summarySpan = $('div.related-info div.indent > span[property="v:summary"]');
  if (summarySpan.length > 0) {
    return summarySpan.text().trim();
  } else {
    return '';
  }
}
function getCatalog($, id) {
  return $(`div.indent#dir_${id}_full`)[0]?.children
    .filter(ele => ele.type === 'text')
    .map(ele => ele.data.remove('\n', '        '))
    .slice(0, -2) || [];
}


function getCoverUrl($) {
  const coverLink = $('div#mainpic>a.nbgnbg');
  if (coverLink.length > 0) {
    return coverLink[0].attribs.href;
  } else {
    return null; // 或者返回一个默认值，表示未找到封面链接
  }
}
function getRating($) {
  const rating = {
    count: 0,
    info: '',
    value: 0,
    five_star_per: 0,
    four_star_per: 0,
    three_star_per: 0,
    two_star_per: 0,
    one_star_per: 0,
  };

  // 获取平均评分
  const averageRatingText = $('strong.ll.rating_num').text().trim();
  if (averageRatingText === '') {
    rating.info = '评分被和谐';
    return rating;
  }
  rating.value = parseFloat(averageRatingText);

  // 获取评价人数
  const votesText = $('div.rating_sum > a.rating_people > span[property="v:votes"]').text().replace('人评价', '');
  if (votesText === '目前无人评价' || votesText === '评价人数不足') {
    rating.info = votesText;
    return rating;
  }
  rating.count = parseInt(votesText);

  // 获取各星级占比
  [
    rating.five_star_per,
    rating.four_star_per,
    rating.three_star_per,
    rating.two_star_per,
    rating.one_star_per
  ] = [...$('div.ratings-on-weight > .item > .rating_per')]
    .map((spanEle) => parseFloat($(spanEle).text().trim().slice(0, -1)));

  return rating;
}

function getComments($) {
  return [...$('div.comment')].map(commentEle => {
    const comment = {};
    const cheerioCommentEle = $(commentEle);

    const commentVoteSpanEle = cheerioCommentEle.find('span.vote-count')[0];
    comment.vote = parseInt(commentVoteSpanEle.children[0].data);

    const commentInfoELe = cheerioCommentEle.find('span.comment-info')[0];
    const cheerioCommentInfoELe = $(commentInfoELe);
    const commentUserAEle = commentInfoELe.children[1];
    comment.user_name = commentUserAEle.children[0].data;
    comment.user_page = commentUserAEle.attribs.href;

    const commentUserStarsSpanELe = cheerioCommentInfoELe.find('span.user-stars')[0];
    comment.rating = {
      力荐: 5,
      推荐: 4,
      还行: 3,
      较差: 2,
      很差: 1,
      不存在: 0
    }[commentUserStarsSpanELe?.attribs?.title || '不存在'];

    const commentTimeSpanEle = cheerioCommentInfoELe.find('a.comment-time')[0];
    comment.date = commentTimeSpanEle?.children[0].data || '';

    const commentContentSpanEle = cheerioCommentEle.find('p.comment-content>span.short')[0];
    comment.content = $(commentContentSpanEle).text();
    return comment;
  });
}

function getReviews($) {
  return [...$('div.review-item')].map(reviewEle => {
    const review = {};
    const cheerioReviewEle = $(reviewEle);
    const cheerioMainHdHeaderEle = cheerioReviewEle.children('header.main-hd');
    const cheerioMainBdDivEle = cheerioReviewEle.children('div.main-bd');

    const avatarImgEle = cheerioMainHdHeaderEle.find('a.avator>img')[0]; // a.avator>img is not a mistake
    review.user_avatar = avatarImgEle.attribs.src;

    const nameAEle = cheerioMainHdHeaderEle.children('a.name')[0];
    review.user_name = nameAEle.children[0].data;
    review.user_page = nameAEle.attribs.href;

    const ratingSpanEle = cheerioMainHdHeaderEle.children('span.main-title-rating')[0];
    ratingSpanEle && (review.rating = { 力荐: 5, 推荐: 4, 还行: 3, 较差: 2, 很差: 1 }[ratingSpanEle.attribs.title] || 0);

    const mainMetaSpanEle = cheerioMainHdHeaderEle.children('span.main-meta')[0];
    review.time = mainMetaSpanEle?.children[0].data || '';

    const publisherAEle = cheerioMainHdHeaderEle.find('span.publisher>a.publisher')[0];
    review.publisher = publisherAEle?.children[0].data || '';
    review.publisher_page = publisherAEle?.attribs.href || '';

    const titleAEle = cheerioMainBdDivEle.find('h2>a')[0];
    review.title = titleAEle.children[0].data;
    review.url = titleAEle.attribs.href;

    const shortContentDivEle = cheerioMainBdDivEle.find('div.short-content')[0];
    review.short_content = shortContentDivEle.children.filter(c => c.type === 'text').map(e => e.data).join('')
      .remove('\n', ' ').slice(0, -3);

    const rUsefulCountSpanEle = cheerioMainBdDivEle.find('span[id^="r-useful_count"]')[0];
    const rUselessCountSpanEle = cheerioMainBdDivEle.find('span[id^="r-useless_count"]')[0];
    review.useful_count = parseInt(rUsefulCountSpanEle.children[0].data.remove('\n', ' ') || '0');
    review.useless_count = parseInt(rUselessCountSpanEle.children[0].data.remove('\n', ' ') || '0');

    const replyAEle = cheerioMainBdDivEle.find('a.reply')[0];
    review.reply_count = parseInt(replyAEle.children[0].data.slice(0, -2));
    return review;
  });
}

// eslint-disable-next-line no-unused-vars
function getNotes($) {
  // TODO
  return [];
}

// 电影详情解析
function parseMovieHTML(html, id) {
  const $ = cheerio.load(html);

  if (!id) {
    id = /douban\.com\/book\/subject\/(\d+)\//.exec(html)[1];
  }
  return {
    subject_id: id,
    title: getTitle($),
    info: getInfo($),
    intro: getIntro($),
    catalog: getCatalog($, id),
    cover_url: getCoverUrl($),
    url: `https://movie.douban.com/subject/${id}/`,
    rating: getRating($),
    comments: getComments($),
    reviews: getReviews($),
    notes: getNotes($),
  };
}

function get_image_list($) {
  const imageList = [];

  // 获取所有包含图片的li元素
  const liElements = $('ul.pics > li');

  // 遍历每个li元素，提取并添加图片链接到数组中
  liElements.each((index, element) => {
    const imgElement = $(element).find('a > img');
    if (imgElement.length) {
      const imageUrl = imgElement.attr('src');
      imageList.push(imageUrl);
    }
  });

  return imageList;
}

function get_image_total($) {
  return parseInt($('div.paginator > .count').text().replace('(共', '').replace('张)', ''));
}

// 演员图库列表解析
function parseCelebrityPhotosHTML(html, artist_id) {
  const $ = cheerio.load(html);
  return {
    artist_id: artist_id,
    image_list: get_image_list($),
    image_total: get_image_total($),
  };
}

/**
 * 演员（基础）信息列表
 * @param {*} $ 
 * @returns 
 */
function getArtistInfoList($) {
  const infoList = [];
  const items = $('ul.subject-property li');

  items.each((i, item) => {
    const span = $(item).find('span');
    let key = span.text().trim().replace(/\s+/g, ' ').replace(/\n/g, '').trim();
    let value = '';
    if (span.next().is('a')) {
      value = { text: span.next().text().trim(), link: span.next().attr('href') };
    } else {
      let li_info_array = key.split(':');
      if (li_info_array.length > 1) {
        value = li_info_array[1].trim();
        key = li_info_array[0].trim();
      }
    }
    infoList.push({ key, value });
  });

  return infoList;
}

/**
 * 演员详情解析
 * @param {*} html 
 * @param {*} subjectId 
 * @returns 
 */
function parseCelebrityHTML(html, artist_id) {
  const $ = cheerio.load(html);
  const name = $('div.avatar-container img.avatar').attr('alt');
  const avatar = $('div.avatar-container img.avatar').attr('src');
  const intro = $('div.desc div.content').text().trim();
  const name_bg = $('div#content h1').text().trim();
  const artist = {
    artist_id: artist_id,
    name: name,
    name_bg: name_bg,
    avatar: avatar,
    intro: intro,
    info: getArtistInfoList($),
  };

  return artist;

}

/**
 * 电影全部演员列表
 * @param {*} $ 
 * @returns 
 */
function getCelebritiesList($, subject_id) {
  const celebritiesList = [];
  const liElements = $('div.article div#celebrities .list-wrapper');
  liElements.each((index, element) => {
    const artist = [];
    $(element).find('.celebrities-list li.celebrity').each((i, celebElement) => {
      const celebrity = {};
      celebrity.name = $(celebElement).find('.info .name a').text().trim();
      celebrity.link = $(celebElement).find('.info .name a').attr('href');
      celebrity.role = $(celebElement).find('.info .role').text().trim();
      celebrity.image = $(celebElement).find('.avatar').css('background-image').replace(/url\(|"|'|\)|"|'/g, '');
      celebrity.representative_works = [];
      $(celebElement).find('.works a').each((j, workElement) => {
        celebrity.representative_works.push({
          title: $(workElement).text().trim(),
          link: $(workElement).attr('href')
        });
      });
      artist.push(celebrity);
    });
    const artistList = {
      role: $(element).find('h2').text().trim(),
      artist: artist,
      subject_id: subject_id
    };
    celebritiesList.push(artistList);
  });
  return celebritiesList;
}

// 电影全部演员列表解析
function parseCelebritiesHTML(html, subjectId) {
  const $ = cheerio.load(html);
  return getCelebritiesList($, subjectId);
}

module.exports = {
  parseMovieHTML,
  parseCelebritiesHTML,
  parseCelebrityHTML,
  parseCelebrityPhotosHTML
};

if (require.main === module) {
  const html = require('fs').readFileSync('.cache/html/id/26807576.html', { encoding: 'utf8' });
  const result = parseMovieHTML(html);
  // require('fs').writeFileSync(`./.cache/result-3221090.json`, JSON.stringify(result, null, 2));
  console.log(result.book_intro);
}
